package com.angel.architecture.persistence.beans;

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.Embeddable;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Parent;

import com.angel.architecture.persistence.base.BusinessObject;
import com.angel.architecture.persistence.base.PersistentObject;

@Embeddable
public class UserRoles extends BusinessObject {

	private static final long serialVersionUID = -8529969759205246292L;

	@Parent
	private User user;

    @ManyToMany(fetch = FetchType.EAGER)
    @Cascade(value = CascadeType.SAVE_UPDATE)
	private Collection<Role> roles = new ArrayList<Role>();

	public UserRoles() {
        super();
	}

	public UserRoles(User parent){
		setUser(parent);
	}

	public User getUser(){
		return this.user;
	}

	public void setUser(User user) {
		this.user = user;
	}



	protected boolean canAccessService(String[] desiredRoles) {
		if ((desiredRoles == null) || (desiredRoles.length == 0))
			return true;

		for (Role role : this.roles)
			if (role.canAccessService(desiredRoles))
				return true;
		return false;
	}

	protected boolean canChangeEntity(String[] desiredRoles, PersistentObject entity) {
		for (Role role : this.roles)
			if (role.canChangeEntity(desiredRoles, entity))
				return true;
		return false;
	}

	public void addRole(Role role) {
		this.roles.add(role);
	}

	public int rolesQty() {
		return this.roles.size();
	}

    public Collection<Role> getRoles() {
        return roles;
    }
}